#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @time     : 2018/2/22 16:42
# @Author   : BYF
# file      : login_case.py
# @version  :

import unittest, os, time, ddt
from base_test import BaseTest
from page.login_page import LoginPage
from common import function
from common.test_data_models import LoginTestDatum as LTD
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC


@ddt.ddt
class LoginTest(BaseTest):
    """登录测试"""

    # 获取测试数据
    # data_file = os.path.dirname(os.path.dirname(__file__)) + "/test_data/login_test_data.csv"
    # test_data = function.get_csv(data_file)

    DB = function.connect_db()
    test_data = DB.query(
        LTD.username,
        LTD.password,
        LTD.excepted,
        LTD.screenshot,
        LTD.type,
    )
    test_data = tuple(test_data)

    # 登录表单验证
    def login_verify(self, username, password):
        LoginPage(self.driver, self.config).login_in(username, password)

    # 此处编写测试用例
    @ddt.data(*test_data)
    @ddt.unpack
    def test_login(self, username, password, expected, screenshot, type):
        """登录测试用例"""

        self.login_verify(username, password)
        try:
            if type == 1:
                WebDriverWait(self.driver, 30, 0.5).until(EC.title_is(u"门店列表"))
                self.assertEqual(self.driver.current_url, expected)
                # 获取cookies 并保存到配置文件
                # cookies = self.driver.get_cookies()
                # if len(cookies) > 0:
                #     function.set_cookies(cookies)
            else:
                WebDriverWait(self.driver, 30, 0.5).until(EC.presence_of_element_located(LoginPage.login_error_loc))
                self.assertEqual(LoginPage(self.driver, self.config).login_error(), expected)
        except Exception as e:
            self.function.get_images(self.driver, screenshot)
            raise e


if __name__ == "__main__":
    unittest.main()
